﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Globalization;
using Microsoft.Phone.Shell;
using CarBloke.ValueConverters;
using System.Windows.Media.Imaging;

namespace CarBloke.Pages
{
    public partial class VehiclePage : PhoneApplicationPage
    {
        private Vehicle _vehicle;

        public VehiclePage()
        {
            InitializeComponent();

            //Application bar and application menu text must be set here explicitly.
            var logButton = ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            var infoButton = ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            logButton.Text = LanguageResources.Resources._log;
            infoButton.Text = LanguageResources.Resources._info;

            var editMenuItem = ApplicationBar.MenuItems[0] as ApplicationBarMenuItem;
            var deleteMenuItem = ApplicationBar.MenuItems[1] as ApplicationBarMenuItem;
            editMenuItem.Text = LanguageResources.Resources._edit;
            deleteMenuItem.Text = LanguageResources.Resources._delete;

            BackgroundImageBrush.ImageSource = ZodiacImage.GetZodiacImage(DateTime.Now);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            Vehicle identifiedVehicle = null;
            string vehicleID = "";
            if (NavigationContext.QueryString.TryGetValue("vehicleID", out vehicleID))
            {
                Guid id = new Guid(vehicleID);
                identifiedVehicle = App.LoadVehicle(id);
            }

            if (identifiedVehicle != null)
            {
                _vehicle = identifiedVehicle;
                VehicleName.Text = identifiedVehicle.Name;
                VehicleYear.Text = identifiedVehicle.Year.ToString();

                if (String.IsNullOrEmpty(identifiedVehicle.Notes))
                {
                    VehicleNotes.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    VehicleNotes.Visibility = System.Windows.Visibility.Visible;
                    VehicleNotes.Text = identifiedVehicle.Notes;
                }                

                FuelEfficiency.Text = "";
                FuelEfficiencyUnits.Text = LanguageResources.Resources.AddMoreLogsLabel;
                currentDateBackground.Visibility = System.Windows.Visibility.Collapsed;

                VehicleStats stats = App.LoadVehicleStats(identifiedVehicle.ID);
                if (stats != null)
                {
                    if (!Double.IsNaN(stats.MostRecentFuelEfficiency) && !Double.IsInfinity(stats.MostRecentFuelEfficiency))
                    {
                        Double lastTankKilomtersPerLiter = stats.MostRecentFuelEfficiency;
                        Double efficiency = UnitConversions.Efficiency(lastTankKilomtersPerLiter, ApplicationSettings.Current.EfficiencyUnit);
                        FuelEfficiency.Text = efficiency.ToString("f", CultureInfo.CurrentCulture);
                        FuelEfficiencyUnits.Text = ApplicationSettings.ToString(ApplicationSettings.Current.EfficiencyUnit);
                    }

                    InitializeMileageCostChart(stats);
                }
            }
        }

        private void InitializeMileageCostChart(VehicleStats stats)
        {
            DateTime date = DateTime.Now;
            var dates = new List<DateValue<Double>>();
            dates.AddRange(stats.Cost);
            dates.AddRange(stats.FuelEfficiency);
            if (dates.Count > 0)
                date = dates.Max(dv => dv.Date);

            date = new DateTime(date.Year - 1, date.Month, date.Day);
            date = date.AddMonths(6);
            Boolean shown = false;

            for(int i = 6; i > 0; i--)
            {
                date = date.AddMonths(1);

                //Total Cost
                double totalCost = double.NaN;
                if (stats.CostMonthlyTotal != null)
                {
                    var dvCost = stats.CostMonthlyTotal.Where(dv => dv.Date.Year == date.Year && dv.Date.Month == date.Month).FirstOrDefault();
                    if (dvCost != null)
                    {
                        totalCost = dvCost.Value;
                    }
                }

                //Average efficiency
                double averageMonthEfficiency = double.NaN;
                if (stats.FuelEfficiencyMonthlyAverage != null)
                {
                    var dvEfficiencyKmL = stats.FuelEfficiencyMonthlyAverage.Where(dv => dv.Date.Year == date.Year && dv.Date.Month == date.Month).FirstOrDefault();
                    if (dvEfficiencyKmL != null)
                    {
                        averageMonthEfficiency = UnitConversions.Efficiency(dvEfficiencyKmL.Value, ApplicationSettings.Current.EfficiencyUnit);
                    }
                }

                //highlight current month
                if (date.Month == DateTime.Now.Month && date.Year == DateTime.Now.Year)
                {
                    Grid.SetRow(currentDateBackground, i-1);
                    currentDateBackground.Visibility = System.Windows.Visibility.Visible;
                }

                switch (i)
                {
                    case 1:
                        shown = configureList(oneMonth, oneCost, oneEfficiency, oneEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 2:
                        shown = configureList(twoMonth, twoCost, twoEfficiency, twoEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 3:
                        shown = configureList(threeMonth, threeCost, threeEfficiency, threeEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 4:
                        shown = configureList(fourMonth, fourCost, fourEfficiency, fourEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 5:
                        shown = configureList(fiveMonth, fiveCost, fiveEfficiency, fiveEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 6:
                        shown = configureList(sixMonth, sixCost, sixEfficiency, sixEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 7:
                        shown = configureList(sevenMonth, sevenCost, sevenEfficiency, sevenEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 8:
                        shown = configureList(eightMonth, eightCost, eightEfficiency, eightEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 9:
                        shown = configureList(nineMonth, nineCost, nineEfficiency, nineEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 10:
                        shown = configureList(tenMonth, tenCost, tenEfficiency, tenEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 11:
                        shown = configureList(elevenMonth, elevenCost, elevenEfficiency, elevenEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                    case 12:
                        shown = configureList(twelveMonth, twelveCost, twelveEfficiency, twelveEfficiencyUnits, totalCost, averageMonthEfficiency, shown, date);
                        break;
                }
            }

        }

        private Boolean configureList(TextBlock month, TextBlock cost, TextBlock efficiency, TextBlock efficiencyUnits, Double totalCost, Double averageMonthEfficiency, Boolean shown, DateTime date)
        {
            if (Double.IsNaN(totalCost) && Double.IsNaN(averageMonthEfficiency) && !shown)
            {
                month.Visibility = System.Windows.Visibility.Collapsed;
                cost.Visibility = System.Windows.Visibility.Collapsed;
                efficiency.Visibility = System.Windows.Visibility.Collapsed;
                efficiencyUnits.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                shown = true;
                if (Double.IsNaN(totalCost) && Double.IsNaN(averageMonthEfficiency))
                {
                    month.Visibility = System.Windows.Visibility.Visible;
                    cost.Visibility = System.Windows.Visibility.Collapsed;
                    efficiency.Visibility = System.Windows.Visibility.Collapsed;
                    efficiencyUnits.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    month.Visibility = System.Windows.Visibility.Visible;
                    cost.Visibility = System.Windows.Visibility.Visible;
                    efficiency.Visibility = System.Windows.Visibility.Visible;
                    efficiencyUnits.Visibility = System.Windows.Visibility.Visible;
                    cost.Text = String.Empty;
                    efficiency.Text = String.Empty;
                    efficiencyUnits.Text = String.Empty;
                }

                month.Text = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[date.Month-1];
                if (!Double.IsNaN(totalCost))
                    cost.Text = totalCost.ToString("c");
                if (!Double.IsNaN(averageMonthEfficiency))
                {
                    efficiency.Text = averageMonthEfficiency.ToString("f");
                    efficiencyUnits.Text = ApplicationSettings.ToString(ApplicationSettings.Current.EfficiencyUnit);
                }
            }

            return shown;
        }

        private void appbar_logButton_Click(object sender, EventArgs e)
        {
            if (_vehicle != null)
                NavigationService.Navigate(new Uri(PageRegistry.VehicleLogPage + "?vehicleID=" + _vehicle.ID.ToString(), UriKind.RelativeOrAbsolute));
            else
                NavigationService.Navigate(new Uri(PageRegistry.VehicleLogPage, UriKind.RelativeOrAbsolute));
        }

        private void appbar_infoButton_Click(object sender, EventArgs e)
        {
            if (_vehicle != null)
                NavigationService.Navigate(new Uri(PageRegistry.VehicleStatsPage + "?vehicleID=" + _vehicle.ID.ToString(), UriKind.RelativeOrAbsolute));
            else
                NavigationService.Navigate(new Uri(PageRegistry.VehicleStatsPage, UriKind.RelativeOrAbsolute));

        }

        private void appbar_editButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(PageRegistry.SelectVehiclePage, UriKind.RelativeOrAbsolute));
        }

        private void deleteMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(LanguageResources.Resources.DeleteVehicleTitle, LanguageResources.Resources.DeleteVehicleWarning, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                App.DeleteVehicle(_vehicle.ID);
                NavigationService.GoBack();
            }
        }

        private void editMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(PageRegistry.VehicleEditPage + "?vehicleID=" + _vehicle.ID, UriKind.RelativeOrAbsolute));
        }
    }
}